<?php

namespace App\Http\Controllers;

use App\Services\SearchService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class SearchController extends Controller
{
    public function __construct(
        private SearchService $searchService
    ) {}

    /**
     * 搜索页面
     */
    public function index(Request $request): Response
    {
        $keyword = $request->input('q', '');
        $type = $request->input('type', 'all'); // all, posts, bars, users

        $results = [];

        if (! empty($keyword)) {
            $searchResults = $this->searchService->search($keyword, $type, 15);

            // 为分页链接添加查询参数
            foreach ($searchResults as $resultType => $result) {
                if ($result instanceof \Illuminate\Pagination\LengthAwarePaginator) {
                    $searchResults[$resultType]->setPath(route('search.index'))
                        ->appends($request->only(['q', 'type']));
                }
            }

            $results = $searchResults;
        }

        return Inertia::render('Search/Index', [
            'keyword' => $keyword,
            'type' => $type,
            'results' => $results,
            'filters' => [
                'q' => $keyword,
                'type' => $type,
            ],
        ]);
    }
}
